package jstudy.gu.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.stereotype.Component;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import lombok.extern.slf4j.Slf4j;

@Aspect // 声明这是一个aop类
@Component // 被spring 所管理 // service @repository
@Slf4j
public class ControllerAspect {
	private static final int slowReq = 3000;// 超过这个时间的,都是接口访问过慢

	private Object runAndSaveLog(ProceedingJoinPoint pjp) throws Throwable {

		long beginTime = System.currentTimeMillis();
		Object result = null;
		Object target = pjp.getTarget();
		Signature signature = pjp.getSignature();
		try {
			result = pjp.proceed(); // 这个方法就是我们实际执行的方法
		} catch (Throwable e) {
//				txmanager.commit(status);
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			e.printStackTrace();
		} finally {

		}
		long endTime = System.currentTimeMillis();
		if (endTime - beginTime > slowReq) {
			// 日志
		}
		log.info("controller : " + target.getClass().getSimpleName());
		log.info("方法 : " + signature.getName());
		log.info("本方法用时: " + (endTime - beginTime));
		// 记录谁访问了这个接口 , 已登录用户
		// 还可以判断接口时间, 统计slowRequest // 便于优化对应的方法
		return result;
	}

	// around 是最强大的
	//
	@Around("@within(org.springframework.stereotype.Controller)")
	Object aroundController(ProceedingJoinPoint pjp) throws Throwable {
		return runAndSaveLog(pjp);
	}

	@Around("@within(org.springframework.web.bind.annotation.RestController)")
	Object aroundRestController(ProceedingJoinPoint pjp) throws Throwable {
		return runAndSaveLog(pjp);
	}
}
